<template>
	<view class="addkehu">
		<headertop :title="title" str1="oridei" :back1="back1"></headertop>
		<image src="https://jingwei.xunfuzhifuzaixian.com/static/images/Rectangle 2@2x.png" mode="widthFix"
			class="addkehuback"></image>
		<view :style="{'margin-top':statusBarHeight+'px','height':barHeight+'px'}"></view>
		<view class="centernr">
			<view class="modeff">
				<view class="modeff_center">
					<view class="modeff_center_line">
						<view class="labletext">
							<span style="color:#F53F3F !important;">*</span>意向项目：
						</view>
						<view class="rightxz" @click="select('意向项目')">
							<span>{{query.hid?text(query.hid,hoselistarr):'请选择'}}</span>
							<image src="https://jingwei.xunfuzhifuzaixian.com/static/images/微信图片_20250806134527.png"
								mode=""></image>
						</view>
					</view>
					<view class="modeff_center_line">
						<view class="labletext">
							<span style="color:#F53F3F !important;">*</span> <span style="color:#86909C">需求产品：</span>
						</view>
						<view class="rightxz">
							<span>{{query.hid?text1(query.hid,hoselistarr):'请选择'}}</span>
						</view>
					</view>
					<view class="modeff_center_line">
						<view class="labletext">
							<span style="color:#F53F3F !important;">*</span>需求面积：
						</view>
						<view class="rightxz">
							<input type="text" placeholder="请输入面积" v-model="query['xqmj']" />
						</view>
					</view>
					<view class="modeff_center_line">
						<view class="labletext" :style="{'color':title=='编辑客户'?'#86909C':''}">
							<span style="color:#F53F3F !important;">*</span>公司名称：
						</view>
						<view class="rightxz">
							<input type="text" :disabled="title=='编辑客户'" placeholder="请输入检索的公司名"
								v-model="query['company']" />
							<image src="https://jingwei.xunfuzhifuzaixian.com/static/images/删除(1).png" @click="qk"
								class="iconrem" style="width: 40rpx !important;height: 40rpx !important;"
								v-if="query['company']&&title!='编辑客户'" mode="" />
							<view class="btn" @click="jiansuo" v-if="title!='编辑客户'">
								检索
							</view>
						</view>
					</view>
					<view class="modeff_center_line">
						<view class="labletext" :style="{'color':title=='编辑客户'?'#86909C':''}">
							<span style="color:#F53F3F !important;">*</span>联系人：
						</view>
						<view class="rightxz">
							<input type="text" :disabled="title=='编辑客户'" placeholder="请输入客户名称"
								v-model="query['username']" />
						</view>
					</view>
					<view class="modeff_center_line">
						<view class="labletext" :style="{'color':title=='编辑客户'?'#86909C':''}">
							<span style="color:#F53F3F !important;">*</span>联系电话：
						</view>
						<view class="rightxz">
							<input type="text" :disabled="title=='编辑客户'" placeholder="请输入电话"
								v-model="query['telphone']" />
						</view>
					</view>
					<view class="modeff_center_line">
						<view class="labletext">
							<span style="color:#F53F3F !important;">*</span><span style="color: #86909C;">行业：</span>
						</view>
						<view class="rightxz" style="width: 300rpx;
    justify-content: flex-end;">
							{{query['hangye']||'--'}}
							<!-- <input type="text" placeholder="--" :disabled="true" v-model="query['hangye']" /> -->
						</view>
					</view>
					<view class="modeff_center_line">
						<view class="labletext">
							<span style="color:#F53F3F !important;">*</span><span style="color: #86909C;">注册地址：</span>
						</view>
						<view class="rightxz" style="width: 300rpx;
    justify-content: flex-end;">
							{{query['zhucedz']||'--'}}
							<!-- <input type="text" placeholder="--" :disabled="true" v-model="query['zhucedz']" /> -->
						</view>
					</view>
					<view class="modeff_center_line">
						<view class="labletext" :style="{'color':title=='编辑客户'?'#86909C':''}">
							微信：
						</view>
						<view class="rightxz">
							<input type="text" placeholder="请输入微信账号" :disabled="title=='编辑客户'"
								v-model="query['weixin']" />
						</view>
					</view>
					<view class="modeff_center_line" style="border: none;">
						<view class="labletext" :style="{'color':title=='编辑客户'?'#86909C':''}">
							<span style="color:#F53F3F !important;">*</span>下次跟进时间：
						</view>
						<view class="rightxz" @click="show1=true" v-if="title!='编辑客户'">
							<input type="text" :disabled="true" placeholder="请选择时间" v-model="query['nexttime']" />
							<image src="https://jingwei.xunfuzhifuzaixian.com/static/images/ww微信图片_20250808181627.png"
								class="rightxzicon" v-if="title!='编辑客户'" mode=""></image>
						</view>
						<view class="rightxz" v-else>
							<input type="text" :disabled="true" placeholder="请选择时间" v-model="query['nexttime']" />
							<image src="https://jingwei.xunfuzhifuzaixian.com/static/images/ww微信图片_20250808181627.png"
								class="rightxzicon" v-if="title!='编辑客户'" mode=""></image>
						</view>
					</view>
				</view>
			</view>

			<view class="modeff" style="margin-top:28rpx;">
				<view class="modeff_center">
					<view class="modeff_center_line">
						<view class="labletext" :style="{'color':title=='编辑客户'?'#86909C':''}">
							<span style="color:#F53F3F !important;">*</span>跟进状态：
						</view>
						<view class="rightxz" @click="select('跟进状态')">
							<span>{{query['status']?text2(query['status'],arree):'请选择'}}</span>
							<image src="https://jingwei.xunfuzhifuzaixian.com/static/images/微信图片_20250806134527.png"
								mode="" v-if="title!='编辑客户'"></image>
						</view>
					</view>
					<view class="modeff_center_line">
						<view class="labletext" :style="{'color':title=='编辑客户'?'#86909C':''}">
							<span style="color:#F53F3F !important;">*</span>跟进方式：
						</view>
						<view class="rightxz" @click="select('跟进方式')">
							<span>{{query['gjtype']?query['gjtype']:'请选择'}}</span>
							<image src="https://jingwei.xunfuzhifuzaixian.com/static/images/微信图片_20250806134527.png"
								mode="" v-if="title!='编辑客户'"></image>
						</view>
					</view>
					<view class="modeff_center_line">
						<view class="labletext" :style="{'color':title=='编辑客户'?'#86909C':''}">
							<span style="color:#F53F3F !important;">*</span>跟进内容：
						</view>
						<view class="rightxz">
							<input type="text" :disabled="title=='编辑客户'" v-model="query['gjneirong']"
								placeholder="请输入跟进内容" />
						</view>
					</view>
					<view class="modeff_center_content">
						<view class="labletext" :style="{'color':title=='编辑客户'?'#86909C':''}">
							相关图片：
						</view>
						<view class="rightxz">
							<view class="image" v-for="(item,index) in images" :key="index">
								<image :src="item" mode=""></image>
								<image src="https://jingwei.xunfuzhifuzaixian.com/static/images/删除.png"
									@click="shanchu(images,index)" class="remivon" mode=""></image>
							</view>
							<view class="uploadimage" @click="uploadImage()" v-if="images.length!=3">
								<image
									src="https://jingwei.xunfuzhifuzaixian.com/static/images/sc微信图片_20250814100310.png"
									mode=""></image>
								<view class="uptext">
									上传图片
								</view>
							</view>
						</view>
					</view>

				</view>
			</view>
			<view class="modeff" style="margin-top:28rpx;">
				<view class="modeff_center">
					<view class="modeff_center_content">
						<view class="labletext" :style="{'color':title=='编辑客户'?'#86909C':''}">
							备注：
						</view>
						<view class="rightxz">
							<textarea name="" id="" :disabled="title=='编辑客户'" v-model="query['beizhu']"
								placeholder="请输入备注内容" cols="30" rows="10"></textarea>
						</view>
					</view>
				</view>
			</view>
		</view>
		<up-picker :show="show" ref="uPickerRef" :columns="areaList" keyName="label" @cancel="cancel" @confirm="confirm"
			:defaultIndex="val" v-if="show"></up-picker>
		<view style="height: 200rpx;">

		</view>
		<view class="fixed">
			<view class="qdbtn" @click="savebtn">
				{{title == '编辑客户'?'确认修改':'确认添加'}}
			</view>
		</view>
		<up-popup :show="show1" mode="bottom">
			<view class="xuanxiang">
				<view class="tt" style="margin-left: 30rpx;color: #888;" @click="show1=false">
					取消
				</view>

				<view class="tt" style="margin-right: 30rpx;color: #0077BE;" @click="queding">
					确认
				</view>
			</view>
			<picker-view immediate-change="true" :indicator-style="indicatorStyle"
				:value="nianyuefun(query['nexttime'])" @change="bindChange" class="picker-view" v-if="show1">
				<picker-view-column>
					<view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
				</picker-view-column>
			</picker-view>
		</up-popup>
	</view>
</template>

<script setup>
	import headertop from '@/components/header.vue'
	import {
		baseUrl
	} from '@/ulm/config';
	import {
		getToken
	} from '@/ulm/utils/auth.js'
	import ulm, {
		$api
	} from '@/ulm';
	import {
		ref,
		onMounted,
		reactive,
	} from 'vue'
	import {
		onLoad,
		onShow,
		onPageScroll,
		onReachBottom
	} from "@dcloudio/uni-app";
	var arree = [{
		label: '新客',
		value: 1
	}, {
		label: '常态跟进',
		value: 2
	}, {
		label: '签订意向协议',
		value: 3
	}, {
		label: '缴纳定金',
		value: 4
	}, {
		label: '签订合同',
		value: 5
	}, {
		label: '缴纳首付款',
		value: 6
	}, {
		label: '缴纳尾款',
		value: 7
	}, {
		label: '已成交',
		value: 8
	}, {
		label: '无效',
		value: 9
	}]
	const back1 = ref('')
	const barHeight = ref('')
	const typestr = ref('')
	const show = ref(false)
	const show1 = ref(false)
	const val = ref([0])
	const uPickerRef = ref(null)
	const areaList = ref([])
	const title = ref('')
	const images = ref([])
	const indicatorStyle = ref(`height: 50px;`)
	const date = new Date()
	const years = []
	const months = []
	const day = date.getDate()
	const month = date.getMonth() + 1
	const days = []
	for (let i = 1900; i <= date.getFullYear(); i++) {
		years.push(i)
	}
	for (let i = 1; i <= 12; i++) {
		months.push(i)
	}
	for (let i = 1; i <= 31; i++) {
		days.push(i)
	}
	const nexttime = ref('')
	const hoselistarr = ref([])
	const statusBarHeight = ref('')
	const query = reactive({
		hid: '',
		xqmj: '',
		company: '',
		username: '',
		telphone: '',
		hangye: '',
		zhucedz: '',
		weixin: '',
		nexttime: '',
		status: '',
		gjtype: '',
		gjneirong: '',
		images: '',
		beizhu: '',
		id: ''
	})
	onLoad((opt) => {
		hoselistinit()
		if (opt.id) {
			query['id'] = opt.id
			title.value = '编辑客户'
			kehufileinit(opt.id)
		} else {
			title.value = '添加客户'
		}
	})
	onPageScroll((e) => {
		if (e.scrollTop > 100) {
			back1.value = '#53ACFF'
		} else {
			back1.value = ''
		}
	})

	function qk() {
		query.company = ''
		query.hangye = ''
		query.zhucedz = ''
	}
	onMounted(() => {
		statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight
		const {
			top,
			height
		} = wx.getMenuButtonBoundingClientRect();
		barHeight.value = height ? height + (top - statusBarHeight.value) * 2 : 38;
	})
	async function kehufileinit(id) {
		const res = await $api.kehufile({
			id
		})
		if (res.code == 1) {
			for (var i in res.data) {
				for (var ii in query) {
					if (i == ii) {
						query[ii] = res.data[i]
					}
				}
			}
			console.log(query, 'queryqueryqueryquery');
		}
	}

	function shanchu(arr, i) {
		arr.splice(i, 1)
	}

	function updateDays(year, month) {
		const daysInMonth = new Date(year, month, 0).getDate();
		var dayss = [];
		for (let i = 1; i <= daysInMonth; i++) {
			dayss.push(i);
		}
		return dayss;
	}

	function bindChange(e) {
		const val = e.detail.value
		days = updateDays(years[val[0]], months[val[1]])
		// if (val[2] >= days.length) {
		// 	val[2] = days.length - 1
		// }
		console.log(val, updateDays(years[val[0]], months[val[1]]), 'val----------------');
		nexttime.value =
			`${years[val[0]]}-${months[val[1]]<10?'0'+months[val[1]]:months[val[1]]}-${days[val[2]]<10?'0'+days[val[2]]:days[val[2]]}`
	}

	async function savebtn() {
		query['images'] = images.value.join()
		console.log(query, 'query=======================');
		for (var i in query) {
			if (i != 'id' && i != 'images' && i != 'beizhu' && i != 'weixin') {
				if (!query[i]) {
					uni.showToast({
						title: '必填项不能为空',
						icon: 'none'
					})
					return
				}
			}
		}
		const phoneRegex = /^1[3-9]\d{9}$/;
		if (!phoneRegex.test(query['telphone'])) {
			uni.showToast({
				title: '请输入正确联系方式',
				icon: 'none'
			})
			return
		}

		const res = await $api.addkehu(query)
		if (res.code == 1) {
			var str = ''
			if (title.value == '编辑客户') {
				str = '编辑'
			} else {
				str = '添加'
			}
			uni.navigateBack()
			uni.showToast({
				title: str + '成功'
			})
		} else {
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
		console.log(query, 'queryqueryqueryquery');
	}

	function uploadImage(str) {
		if (title.value == '编辑客户') return
		uni.chooseImage({
			count: 3 - images.value.length, // 最多可选择图片数量
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
			success: (res) => {
				const validImages = res.tempFiles.filter(file => {
					return file.size <= 2 * 1024 * 1024; // 2MB = 2 * 1024 * 1024 Bytes
				});
				if (validImages.length === 0) {
					uni.showToast({
						title: `${res.tempFiles.length - validImages.length}张图片超过2MB`,
						icon: 'none'
					});
					return;
				}
				// tempFilePath 可以作为 img 标签的 src 属性显示图片
				const tempFilePaths = res.tempFilePaths
				uploadImages(tempFilePaths, str)
			},
			fail: (err) => {

			}
		})
	}

	function uploadImages(filePaths, str) {
		const uploadTasks = filePaths.map((filePath, index) => {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: `${baseUrl}/api/common/upload`,
					filePath: filePath,
					name: 'file',
					formData: {
						index: index // 可以添加序号标识
					},
					header: {
						token: getToken()
					},
					success: (uploadRes) => {
						resolve(JSON.parse(uploadRes.data))
					},
					fail: (err) => {
						reject(err)
					}
				})
			})
		})

		uni.showLoading({
			title: '上传中...'
		})

		Promise.all(uploadTasks)
			.then(results => {
				for (var i in results) {
					images.value.push(results[i]['data']['fullurl'])
				}
				uni.hideLoading()

				uni.showToast({
					title: `成功上传${results.length}张图片`,
					icon: 'success'
				})
			})
			.catch(err => {
				uni.hideLoading()
			})
	}

	function queding() {
		if (!nexttime.value) {
			query['nexttime'] =
				`${date.getFullYear()}-${months[month-1]<10?'0'+months[month-1]:months[month-1]}-${day<10?'0'+day:day}`
		} else {
			query['nexttime'] = nexttime.value
		}
		show1.value = false
	}

	function nianyuefun(str) {
		if (!str) {
			return [9999, month - 1, day - 1]
		} else {
			var arr = str.split('-')
			var ind1 = years.findIndex(item => item == arr[0])
			var ind2 = months.findIndex(item => item == arr[1])
			var ind3 = days.findIndex(item => item == arr[2])
			return [ind1, ind2, ind3]
		}

	}

	function text(id, arr) {
		var ind = arr.findIndex(item => item.id == id)
		if (ind == -1) return
		return arr[ind]['title']
	}

	function text2(id, arr) {
		var ind = arr.findIndex(item => item.value == id)
		if (ind == -1) return
		return arr[ind]['label']
	}

	function text1(id, arr) {
		var ind = arr.findIndex(item => item.id == id)
		if (ind == -1) return
		return arr[ind]['product'].join()
	}

	async function hoselistinit() {
		const res = await $api.hoselist({
			page: 1,
			limit: 100
		})
		if (res.code == 1) {
			hoselistarr.value = res.data.list
		}
	}
	// 点击下拉框选择
	const select = async (e) => {
		typestr.value = e
		if (title.value == '编辑客户' && e != '意向项目') return
		if (e == '意向项目') {

			var arr = []
			for (var i in hoselistarr.value) {
				var obj = {
					'label': hoselistarr.value[i]['title'],
					'value': hoselistarr.value[i]['id'],
				}
				arr.push(obj)
			}
			areaList.value = [arr]
			if (!query.hid) {
				val.value = [0]
			} else {
				var ind = arr.findIndex(item => item.value == query.hid)
				val.value = [ind]
			}

		} else if (e == '跟进状态') {
			if (!query.status) {
				val.value = [0]
			} else {
				var ind = arree.findIndex(item => item.value == query.status)
				val.value = [ind]
			}
			areaList.value = [arree]
		} else if (e == '跟进方式') {
			const res = await $api.baifang()
			if (res.code == 1) {
				var arr = []
				for (var i in res.data) {
					var obj = {
						'label': res.data[i]['title'],
						'value': res.data[i]['title'],
					}
					arr.push(obj)
				}
				areaList.value = [arr]
				if (!query.gjtype) {
					val.value = [0]
				} else {
					var ind = arr.findIndex(item => item.value == query.gjtype)
					val.value = [ind]
				}
			}
		}
		show.value = true

	}
	async function jiansuo() {
		if (title.value == '编辑客户') return
		if (!query['company']) {
			uni.showToast({
				title: '检索名称不能为空',
				icon: 'none'
			})
			return
		}
		const res = await $api.searchcom({
			name: query['company'],
			page: 1
		})
		if (res.code == 1) {
			var arr = []
			for (var i in res.data.items) {
				var obj = {
					'label': res.data.items[i]['name'],
					'value': res.data.items[i]['name'],
				}
				arr.push(obj)
			}
			areaList.value = [arr]
			typestr.value = '公司名称'
			show.value = true
		} else {
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}

	}
	const confirm = async (e) => {
		let {
			value
		} = e
		console.log(e, 'eeee');
		if (typestr.value == '意向项目') {
			query['hid'] = value[0]['value']
		}
		if (typestr.value == '公司名称') {
			query['company'] = value[0]['value']
			companyfileinit()
		}
		if (typestr.value == '跟进状态') {
			query['status'] = value[0]['value']
		}
		if (typestr.value == '跟进方式') {
			query['gjtype'] = value[0]['value']
		}
		show.value = false;
	}
	async function companyfileinit() {
		const res = await $api.companyfile({
			name: query['company']
		})
		if (res.code == 1) {
			query.zhucedz = res.data.regLocation
			query.hangye = res.data.industry
		}
	}

	const cancel = () => {
		show.value = false;
	}
</script>

<style lang="scss">
	.xuanxiang {
		width: 100%;
		display: flex;
		align-items: center;
		margin-top: 30rpx;
		overflow: hidden;
		justify-content: space-between;
		margin-bottom: 30rpx;

		.tt {
			font-size: 32rpx;
		}
	}

	.picker-view {
		width: 100%;
		height: 600rpx;
		margin-top: 20rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 0 0;
	}

	.item {
		line-height: 100rpx;
		text-align: center;
	}


	::v-deep .u-popup__content {
		border-radius: 20rpx 20rpx 0 0;
	}

	page {
		background: #F7F8FA;
	}

	.fixed {
		width: 100%;
		position: fixed;
		bottom: 0%;
		background: #FFFFFF;
		overflow: hidden;
		z-index: 9999;
		box-shadow: 0rpx -6rpx 14rpx 0rpx rgba(0, 0, 0, 0.03);

		.qdbtn {
			width: 686rpx;
			height: 90rpx;
			background: #13A2E6;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			text-align: center;
			line-height: 90rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #FFFFFF;
			margin: auto;
			margin-top: 20rpx;
			margin-bottom: 84rpx;
		}
	}

	.addkehu {
		width: 100%;
		overflow: hidden;
		position: relative;

		.addkehuback {
			width: 100%;
			position: absolute;
			z-index: -1;
		}

		.centernr {
			width: 686rpx;
			margin: auto;
			margin-top: 32rpx;
			overflow: hidden;

			.modeff {
				width: 100%;
				background: #FFFFFF;
				box-shadow: 0rpx 4rpx 10rpx 0rpx rgba(0, 0, 0, 0.03);
				border-radius: 24rpx 24rpx 24rpx 24rpx;
				overflow: hidden;

				&_center {
					width: 630rpx;
					margin: auto;

					&_content {
						width: 100%;
						overflow: hidden;

						.labletext {
							font-family: PingFang SC, PingFang SC;
							font-weight: 400;
							font-size: 28rpx;
							color: #1D2129;
							margin-top: 28rpx;
						}

						.rightxz {
							width: 100%;
							margin-top: 20rpx;
							display: flex;
							flex-wrap: wrap;
							align-items: center;
							font-size: 28rpx;
							margin-bottom: 36rpx;

							.iconrem {
								width: 40rpx !important;
								height: 40rpx !important;
							}

							.image {
								height: 188rpx;
								width: 228rpx;
								border-radius: 16rpx 16rpx 16rpx 16rpx;
								position: relative;
								margin-right: 30rpx;
								margin-bottom: 10rpx;



								image {
									height: 188rpx;
									width: 228rpx;
									border-radius: 16rpx 16rpx 16rpx 16rpx;
									overflow: hidden;
								}

								.remivon {
									position: absolute;
									width: 30rpx;
									height: 30rpx;
									top: -6%;
									right: -6%;
									z-index: 9999;
								}
							}

							.uploadimage {
								width: 228rpx;
								overflow: hidden;
								border-radius: 16rpx 16rpx 16rpx 16rpx;
								position: relative;
								margin-right: 30rpx;
								margin-bottom: 10rpx;

								image {
									height: 188rpx;
									width: 228rpx;
								}

								.uptext {
									width: 100%;
									text-align: center;
									position: absolute;
									bottom: 32rpx;
									z-index: 99;
									font-family: PingFang SC, PingFang SC;
									font-weight: 400;
									font-size: 24rpx;
									color: #86909C;
								}
							}

							.rightxzicon {
								width: 32rpx;
								height: 32rpx;
							}

							.btn {
								width: 80rpx;
								height: 50rpx;

							}

							::v-deep textarea {
								height: 100rpx;
								width: 100%;
								font-size: 28rpx;
							}
						}


					}

					&_line {
						width: 100%;
						display: flex;
						justify-content: space-between;
						align-items: center;
						min-height: 88rpx;
						border-bottom: 2rpx solid #F2F3F5;

						.labletext {
							font-family: PingFang SC, PingFang SC;
							font-weight: 400;
							font-size: 28rpx;
							color: #1D2129;
						}

						.rightxz {
							display: flex;
							align-items: center;
							font-family: PingFang SC, PingFang SC;
							font-weight: 400;
							font-size: 28rpx;
							color: #86909C;

							.btn {
								color: #fff;
								width: 80rpx;
								height: 50rpx;
								line-height: 50rpx;
								text-align: center;
								background: #86909C;
								border-radius: 10rpx;
								margin-left: 20rpx;
							}

							input {
								font-family: PingFang SC, PingFang SC;
								font-weight: 400;
								font-size: 28rpx;
								color: #86909C;
								text-align: right;
								width: 330rpx;
							}

							image {
								width: 24rpx;
								height: 24rpx;
								margin-left: 8rpx;
							}
						}
					}
				}
			}
		}
	}
</style>